package com.app.base;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.app.exception.BusinessExceptionHandler;
import com.app.request.CriterionRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @ControllerAdvice 和 @RestControllerAdvice都是对Controller和RestController进行增强的，可以全局捕获spring mvc抛的异常。
 * 这样我们的controller中就不需要再去写大量的try-catch了，RestControllerAdvice会自动帮助catch,
 * 并匹配相应的ExceptionHandler,然后重新封装异常信息，返回值，统一格式返回给前端。
 */
@Slf4j
@RestControllerAdvice
public class BaseController extends BusinessExceptionHandler {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 分页参数提取
     */

    protected ThreadLocal<Page> page = new ThreadLocal<>();

    protected void startPage(CriterionRequest request) {
        page.set(PageHelper.startPage(request.getPage(), request.getLimit(), request.orderBy()));
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false  ));
    }


}
